﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BEGDC.PreContract.BLL;

namespace PreContractWeb.Administration
{
    public partial class EditCloseDate : System.Web.UI.Page
    {
        private BEGDC.PreContract.BLL.Authentication.PCIdentity user;

        protected void Page_Load(object sender, EventArgs e)
        {

            Page.Header.Controls.Add(new LiteralControl(@"<base target=""_self"" />"));

            user = new BEGDC.PreContract.BLL.Authentication.PCIdentity(HttpContext.Current.User.Identity);

            if (!ReportHelper.IsAdmin(user.EmployeeId))
            {
                this.divError.InnerHtml = AlertMessage.NoAdminPermission;
                this.divConnect.Visible = false;
                this.divError.Visible = true;
            }

            else if (!IsPostBack)
            {
                if (Request["id"] != null)
                    if (Request["id"] == "-1")
                    {
                        this.SaveButton.Text = "添加(Add)";
                        this.CNTitleLabel.Text = "添加关账日期";
                        this.ENTitleLabel.Text = "Add A CloseDate";
                        this.MonthLabel.CssClass = "required";
                        this.MonthLabel.Text = "*";
                        this.YearLabel.CssClass = "required";
                        this.YearLabel.Text = "*";
                        this.YearTextBox.Visible = true;
                        this.MonthDropDownList.Visible = true;

                        for (int i = 1; i < 13; i++)
                        {
                            this.MonthDropDownList.Items.Add(i.ToString());
                        }
                    }
                    else
                    {
                        this.SaveButton.Text = "保存(Save)";
                        this.CNTitleLabel.Text = "编辑关账日期信息";
                        this.ENTitleLabel.Text = "Edit CloseDate Information";
                        this.LoadData();
                    }

                Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }
        }

        protected void LoadData()
        {
            try
            {
                int closeDateID = int.Parse(Request["id"].ToString());

                BEGDC.PreContract.BLL.ICloseDate iCloseDate = (BEGDC.PreContract.BLL.ICloseDate)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_CloseDate_Service];
                BEGDC.PreContract.DAL.CloseDate closeDate = iCloseDate.GetCloseDate(closeDateID);

                this.YearLabel.Text = closeDate.Year.ToString();
                this.MonthLabel.Text = closeDate.Month.ToString();
                this.EndDateTextBox.Text = String.Format("{0:yyyy-MM-dd}",closeDate.EndDate);

                if (closeDate.Year < Convert.ToInt32(DateTime.Now.Year))
                {
                    this.SaveButton.Enabled = false;
                    this.CNTitleLabel.Text = "查看";
                    this.ENTitleLabel.Text = "View";

                    this.EndDateTextBox.ReadOnly = true;
                }
            }

            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
 
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                int closeDateID = int.Parse(Request["id"].ToString());
                
                BEGDC.PreContract.BLL.ICloseDate iCloseDate = (BEGDC.PreContract.BLL.ICloseDate)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_CloseDate_Service];
                BEGDC.PreContract.DAL.CloseDate closeDate = new BEGDC.PreContract.DAL.CloseDate();

                if (closeDateID == -1)
                {
                    int year = Convert.ToInt32(this.YearTextBox.Text.Trim());
                    int month = Convert.ToInt32(this.MonthDropDownList.SelectedValue);
                    DataTable dt = iCloseDate.GetCloseDate_DataTable(String.Format("Year = {0} AND Month = {1}",year,month));

                    if (dt.Rows.Count != 0)
                    {
                        this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('管账日期已存在\\nCloseDate is already exist')</script>");
                        return;
                    }

                    else
                    {
                        DateTime endDate = Convert.ToDateTime(this.EndDateTextBox.Text.Trim());

                        if (this.CheckDate(endDate, year, month))
                        {
                            int quarter = month % 4;
                            closeDate.Year = year;
                            closeDate.Month = month;
                            closeDate.Quarter = quarter;
                            closeDate.EndDate = endDate;
                            closeDate.StartDate = new DateTime(year, month, 1);
                            closeDate.Create();

                            iCloseDate.SetTradeMonth(closeDate.CloseDateID);
                        }
                        else
                        {
                            this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择关帐日在当年当月\\nPlease select the close date within the year and month.')</script>");
                            return;
                        }
                    }
                }
                else
                {
                    closeDate = iCloseDate.GetCloseDate(closeDateID);
                    DateTime inputDate = Convert.ToDateTime(this.EndDateTextBox.Text.Trim());
                    
                    if (!this.CheckDate(inputDate,closeDate))
                    {
                        this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择关帐日在当年当月\\nPlease select the close date within the year and month.')</script>");
                        return;
                    }
                    else
                    {
                        closeDate.EndDate = Convert.ToDateTime(this.EndDateTextBox.Text.Trim());
                        closeDate.Update();
                        iCloseDate.SetTradeMonth(closeDate.CloseDateID);
                    }
                }

                BaseFunction.CreateLog(BEGDC.PreContract.BLL.OperationLog.OperationType.EditCloseDate, string.Format("StartDate: {0}; EndDate: {1}", closeDate.StartDate.Value.ToString("yyyy-MM-dd"), closeDate.EndDate.Value.ToString("yyyy-MM-dd")), User.Identity.Name);

                this.Response.Write("<script language='javascript'>alert('" + BaseFunction.ChangeAlertMessage(AlertMessage.OperationSuccess) + "');var arr=new Array(); arr[0]="+closeDate.Year+"; window.returnValue=arr;window.close();</script>");
                
            }
            catch (Exception ex)
           {
               this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
           }
        }

        /// <summary>
        /// Check the end date when adding
        /// </summary>
        /// <param name="inputDate"></param>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        private bool CheckDate(DateTime inputDate,int year,int month)
        {
            int inputYear = inputDate.Year;
            int inputMonth = inputDate.Month;

            if (inputMonth == month && inputYear == year)
                return true;
            else
                return false;
        }

        /// <summary>
        /// Check the end date when modifying
        /// </summary>
        /// <param name="inputDate"></param>
        /// <param name="closeDate"></param>
        /// <returns></returns>
        private bool CheckDate(DateTime inputDate, BEGDC.PreContract.DAL.CloseDate closeDate)
        {
            int inputYear = inputDate.Year;
            int inputMonth = inputDate.Month;
            int year = closeDate.Year;
            int month = closeDate.Month;

            if (inputMonth == month && inputYear == year)
                return true;
            else
                return false;
        }

       
        
    }
}
